package com.train.api;

import java.io.File;
import java.util.List;
import java.util.Random;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;

public class Util {
	public static void AddHeaders(HttpPost method){
		method.addHeader("User-Agent",      "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)");
		method.addHeader("Content-Type",    "application/x-www-form-urlencoded");
		method.addHeader("Accept",          "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap,");
		method.addHeader("Cache-Control",   "no-cache");
		method.addHeader("Connection",      "Keep-Alive");
		method.addHeader("Referer",         "http://dynamic.12306.cn/TrainQuery/ticketPriceByStation.jsp");
		method.addHeader("Accept-Language", "zh-CN");
		method.addHeader("Host",            "dynamic.12306.cn");
	}
	
	public static void AddHeaders(HttpGet method){
		method.addHeader("User-Agent",      "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)");
		method.addHeader("Content-Type",    "application/x-www-form-urlencoded");
		method.addHeader("Accept",          "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap,");
		method.addHeader("Cache-Control",   "no-cache");
		method.addHeader("Connection",      "Keep-Alive");
		method.addHeader("Referer",         "http://dynamic.12306.cn/TrainQuery/ticketPriceByStation.jsp");
		method.addHeader("Accept-Language", "zh-CN");
		method.addHeader("Host",            "dynamic.12306.cn");
	}
	
	public static void AddHeaders2(HttpGet method){
		method.addHeader("User-Agent",      "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)");
		method.addHeader("Cache-Control",   "max-age=0");
		method.addHeader("Accept",          "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		method.addHeader("Connection",      "Keep-Alive");
		method.addHeader("Accept-Language", "zh-CN");
		method.addHeader("Host",            "dynamic.12306.cn");
	}
	
	public static byte[] Post(String URL, List<NameValuePair> data, HttpContext localContext, CookieStore cookieStore){
		HttpClient client = getClient();
		HttpPost httpPost = new HttpPost(URL);
		
		byte[] result = null;
		try{
			AddHeaders(httpPost);
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			httpPost.setEntity((new UrlEncodedFormEntity(data, "UTF-8")));
			HttpResponse resp = client.execute(httpPost, localContext);
			
			result = EntityUtils.toByteArray(resp.getEntity());
		}catch(Exception e){
			result = null;
		}finally{
			//httpPost.releaseConnection();
		}
		return result;
	}
	
	public static byte[] Post(String URL, String data, HttpContext localContext, CookieStore cookieStore){
		HttpClient client = getClient();
		HttpPost httpPost = new HttpPost(URL);
		
		byte[] result = null;
		try{
			AddHeaders(httpPost);
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			httpPost.setEntity((new StringEntity(data, "UTF8")));
			HttpResponse resp = client.execute(httpPost, localContext);
			result = EntityUtils.toByteArray(resp.getEntity());
		}catch(Exception e){
			result = null;
		}finally{
			//httpPost.releaseConnection();	
		}
		return result;
	}

	public static byte[] Get(String URL, List<NameValuePair> data, HttpContext localContext, CookieStore cookieStore){
		HttpClient client = getClient();
		HttpGet httpGet = null;
		
		byte[] result = null;
		try{
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			String params = "";
			for (int i = 0; i < data.size(); i++){
				NameValuePair temp = data.get(i);
				if (!params.equals("")){
					params += "&";
				}
				params += String.format("%s=%s", temp.getName(), temp.getValue());
			}
			if (!params.equals("")){
				URL += "?" + params;
				System.out.println(URL);
			}
			httpGet = new HttpGet(URL);
			AddHeaders2(httpGet);
			HttpResponse resp = client.execute(httpGet, localContext);
			result = EntityUtils.toByteArray(resp.getEntity());
		}catch(Exception e){
			System.out.println(e);
			result = null;
		}finally{
			//httpGet.releaseConnection();
		}
		return result;
	}
	
	public static byte[] Get(String URL, HttpContext localContext, CookieStore cookieStore){
		HttpClient client = getClient();
		HttpGet httpGet = new HttpGet(URL);
		
		byte[] result = null;
		try{
			AddHeaders(httpGet);
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			HttpResponse resp = client.execute(httpGet, localContext);
			if (resp.getStatusLine().getStatusCode() == 200){
				result = EntityUtils.toByteArray(resp.getEntity());
			}
		}catch(Exception e){
			result = null;
		}finally{
			//httpGet.releaseConnection();
		}
		return result;
	}
	
	public static HttpClient getClient(){
		HttpClient httpClient = new DefaultHttpClient();
		/*
        X509TrustManager xtm = new X509TrustManager(){     
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}  
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}  
            public X509Certificate[] getAcceptedIssuers() { return null; }  
        };  
        try {    
            SSLContext ctx = SSLContext.getInstance("TLS");    
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);  
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); 
        }catch(Exception e){
        	System.out.println(e);
        }
        */
        return httpClient;   
	}
	
	public static String rand(){
		Random random = new Random();
		return Double.toString(random.nextDouble());
	}
	
	public static boolean deleteFile(String path){
		boolean result = false;
		if (path != null){
			File file = new File(path);
			if (file.isDirectory()){
				File[] oldFileList = file.listFiles();
				for (int i = 0; i < oldFileList.length; i++){
					File temp = oldFileList[i];
					if (temp.exists()){
						temp.delete();
					}
				}
				result = true;
			}
		}
		return result;
	}
}
